<?php

namespace app\admin\controller\facrm\apps;

use app\common\controller\Backend;
use think\Queue;
use think\Validate;

/**
 * 邮件模板
 * @icon fa fa-tags
 */
class Email extends Backend
{

    protected $key = "emalitpl_setting_lists";
    protected $addon_config = array();
    protected $noNeedRight = ['selectpage'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\facrm\Setting();

    }

    /**
     * 查看列表
     * @return string|\think\response\Json
     * @throws \think\Exception
     */
    public function index()
    {

        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                $this->request->request(['custom' => ['key' => $this->key]]);
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->where('key', $this->key)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $total = $this->model
                ->where($where)
                ->where('key', $this->key)
                ->order($sort, $order)
                ->count();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     * @return mixed
     */
    public function add()
    {


        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if (empty($params['values'])) $this->error(—);
            $this->request->post(['row' => array_merge($params, [
                'values' => json_encode($params['values'])
            ])]);
        }
        $this->addon_config = get_addon_config('facrm');
        $this->view->assign("recordTypeList", $this->addon_config['record_type']);
        $this->view->assign('key', $this->key);
        return parent::add();
    }

    /**
     * 修改
     * @return mixed
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if (empty($params['values'])) $this->error();
            $this->request->post(['row' => array_merge($params, [
                'values' => json_encode($params['values'])
            ])]);
        }
        $this->view->assign('key', $this->key);
        $this->addon_config = get_addon_config('facrm');
        $this->view->assign("recordTypeList", $this->addon_config['record_type']);
        return parent::edit($ids);
    }

    /**
     * 发邮件
     */
    public function send()
    {

        $data = $this->request->param('data');
        $data = json_decode($data, true);
        $types_data = array();//发送对象数据，如客户，联系人
        if ($data && $data['types']) {
            $auth = new \addons\facrm\library\Auth();
            //TODO 还可以精简，为了明了，暂时不做
            switch ($data['types']) {
                case "customer":
                    $custModel = new \app\admin\model\facrm\Customer();
                    $types_data = $custModel->find($data['typesid']);

                    if (!$auth->checkCustomerAuth($types_data, $this->auth)) {
                        $this->error(__('您没有权限'));
                    }
                    break;
                case "business":
                    $custModel = new \app\admin\model\facrm\Customer();
                    $types_data = $custModel->find($data['customer_id']);
                    if (!$auth->checkCustomerAuth($types_data, $this->auth)) {
                        $this->error(__('您没有权限'));
                    }
                    break;
                case "contacts":
                    $contactsModel = new \app\admin\model\facrm\customer\Contacts();
                    $types_data = $contactsModel->find($data['typesid']);
                    if (!$types_data) break;
                    if (!$auth->checkCustomerAuth($types_data['customer_id'], $this->auth)) {
                        $this->error(__('您没有权限'));
                    }
                    break;
                case "clues":
                    $custModel = new \app\admin\model\facrm\Clues();
                    $types_data = $custModel->find($data['typesid']);
                    if (!$auth->checkCluesAuth($types_data, $this->auth)) {
                        $this->error(__('您没有权限'));
                    }
                    break;
                default:
                    break;
            }
        }

        if ($types_data){
            $types_data = $types_data->toArray();
        }

        $email_id = $this->request->param('email_id', '', 'intval');
        $config_row = array();
        if ($email_id) {
            $config_row = $this->model
                ->where('key', $this->key)->find($email_id);
            $values=$config_row['values'] = json_decode($config_row['values'], true);
            if ( isset($values['content'])){
                //参数格式化
                $values['content']=(__($values['content'],$types_data));
                $config_row['values']=$values;
            }

        }

        if ($this->request->isPost()) {
            $row = $this->request->post('row/a');
            if ($row['email']) {
                if (!Validate::is($row['email'], "email")) {
                    $this->error(__('邮箱有误'));
                }

                //邮件队列
                $data = array_merge($data,[
                    'subject' => $row['title'],
                    'to' => $row['email'],
                    'message' => __($row['content'], $types_data),
                ]);


                Queue::push("addons\\facrm\\library\\queue\\EmailJob", $data);
                //邮件队列end
                if (true) {
                    //param_data types类型如customer,contacts| typesid对应的ID
                    //send_data发送邮件的内容
                    //types_data 当前对象的数据
                    $row['create_user_id'] = $this->auth->id;//用于标明是谁发送的
                    $row['record_type']=isset($config_row['values']['record_type']) ? $config_row['values']['record_type'] : 0;//跟进类型
                    hook("facrm_send_email_success", array('param_data' => $data, 'send_data' => $row, 'types_data' => $types_data));
                    $this->success();
                }
            } else {
                $this->error(__('Invalid parameters'));
            }
        }


        return $this->view->fetch('', ['row' => $config_row, 'types_data' => $types_data]);

    }

    /**
     * 批量邮件发送
     * @return string
     * @param $data['types'] //发送配置，types：customer，contacts
     * @param $data['typesid'] //对象集合ID，多个以逗号隔开
     * @param $data['title'] //邮件标题
     * @param $data['message'] //邮件正文
     * @param $data['create_user_id'] //邮件发送人ID
     * @param $data['record_type'] //跟进类型ID
     */
    public function sends()
    {

        $data = $this->request->param('data');
        $data = json_decode($data, true);

        if ($this->request->isPost()) {
            $row = $this->request->post('row/a');

            //TODO 未判断选择客户和联系人的权限
            //邮件队列
            $row['create_user_id']=$this->auth->id;
            $data =array_merge($data,$row);
            Queue::push("addons\\facrm\\library\\queue\\EmailsJob", $data);
            $this->success();
        }
        $types_data = array();//发送对象数据，如客户，联系人
        if ($data && $data['types']) {
            switch ($data['types']) {
                case "customer":
                    $custModel = new \app\admin\model\facrm\Customer();
                    $types_data = $custModel->where('id','in',$data['typesid'])->find();
                    break;
                case "contacts":
                    $contactsModel = new \app\admin\model\facrm\customer\Contacts();
                    $types_data = $contactsModel->where('id','in',$data['typesid'])->find();
                    break;
                default:
                    break;
            }
        }

        if ($types_data){
            $types_data = $types_data->toArray();
        }

        $email_id = $this->request->param('email_id', '', 'intval');
        $row = array();
        if ($email_id) {
            $row = $this->model
                ->where('key', $this->key)->find($email_id);
            $values=$row['values'] = json_decode($row['values'], true);
            if ( isset($values['content'])){
                //参数格式化
                $values['content']=(__($values['content'],$types_data));
                $row['values']=$values;
            }
        }
        return $this->view->fetch('', ['row' => $row,'types_data'=>$types_data]);
    }

    /**
     * 选择模板
     * @Internal
     * @return \think\response\Json
     */
    public function selectpage()
    {
        $this->request->request(['custom' => ['key' => $this->key,'status'=>1]]);
        return parent::selectpage(); // TODO: Change the autogenerated stub
    }
}